#include "bsp_sleep.h"
/*!
    \brief      software reset mcu
    \param[in]  none
    \param[out] none
    \retval     none
*/
void mcu_software_reset(void)
{
    /* set PRIMASK */
    __set_PRIMASK(1);
    NVIC_SystemReset();
}

void sys_sleep( uint8_t *state)
{
    uint16_t tick = 0;
   

sleep_loop:
    bsp_InitKey();
    adc_disable();
    PUMP_stop();
    LED_POWER_CLOSE();
    vTaskDelay(100);    
    DC_5V_DIS();
    vTaskDelay(10);    
    led_display_off_all();
    vTaskDelay(10);    

    gpio_deinit_init();
    wakeup_key_init();
    pmu_to_deepsleepmode(PMU_LDO_LOWPOWER, WFI_CMD);
    
    SystemInit();
    systick_config();
    adc_config();
    pwm_init();
    gpio_init();


    while(1)
    {
        tick++;
        
        if((gpio_input_bit_get(GPIOB,GPIO_PIN_3) == 0) && (tick>5))
        {
            if(low_power_state == pdTRUE)
            {
                *state = 3;
                break;
                
            }
            else
            {
                *state = 1;
                break;
            }
            
        }
        else if(GET_CHARGE_CHECK_CHRG() == 0)
        {
            *state  = 2;
            low_power_state = pdFALSE;
            break;
        }
        
        else if((gpio_input_bit_get(GPIOB,GPIO_PIN_3) == 1) && (tick>50))
        {
            goto sleep_loop;
        }
        vTaskDelay(10);
    }
   LED_POWER_OPEN();
    DC_5V_EN();   
    vTaskDelay(500);
    led_display_off_all();
    led_display_init();
}


void EXTI2_3_IRQHandler(void)
{
    if(SET == exti_interrupt_flag_get(EXTI_3)){
        exti_interrupt_flag_clear(EXTI_3);
    }
}

void EXTI4_15_IRQHandler(void)
{
    if(SET == exti_interrupt_flag_get(EXTI_5)){
        exti_interrupt_flag_clear(EXTI_5);
    }
}
